package com.zc.controller;

import com.zc.annotation.SystemLogAnnotation;
import com.zc.dto.LoginDto;
import com.zc.dto.SysResourceDto;
import com.zc.service.SysAccountService;
import com.zc.service.SysResourceService;
import com.zc.utils.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 登录
 */

@Controller
@RequestMapping("auth")
@Slf4j
public class LoginController {

    @Autowired
    private SysAccountService sysAccountService;

    @Autowired
    private SysResourceService sysResourceService;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @SystemLogAnnotation("用户登录")
    @PostMapping("login")
    public String login(String username, String password, HttpSession session
            , RedirectAttributes attributes, Model model) {

        JSONResult jsonResult = sysAccountService.login(username, password);
        LoginDto loginDTO = (LoginDto) jsonResult.getData();

        if (jsonResult.isOK()) {
            session.setAttribute("sysAccount", loginDTO.getSysAccount());
            //查询该用户下权限的菜单
            List<SysResourceDto> sysResourceVoList = sysResourceService.listSysResourceByRoleId(loginDTO.getSysAccount().getRoleId());
            model.addAttribute("sysResourceVoList", sysResourceVoList);
        } else {
            attributes.addFlashAttribute(jsonResult.getErrorMsg());
        }

        return loginDTO.getPath();
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @SystemLogAnnotation("退出登录")
    @GetMapping("logout")
    public String login(HttpSession session) {

        //销毁session
        session.invalidate();

        return "redirect:/";
    }
}
